from sqlalchemy import Column, Integer, VARCHAR, TEXT, SmallInteger, and_, or_
from src.db.database import Base
from src.db.database import sqldb
from typing import List, Optional
from src.util.log import log


class Ticket(Base):
    __tablename__ = 'ticket'

    id = Column(Integer, primary_key=True, autoincrement=True)
    train_number = Column(VARCHAR(255))
    seat = Column(VARCHAR(255))
    ticket_entrance = Column(TEXT)
    start_place = Column(TEXT)
    end_place = Column(TEXT)
    time = Column(VARCHAR(255))
    date = Column(VARCHAR(255))
    dingding_event_id = Column(TEXT, default="")
    order_no = Column(VARCHAR(255))
    is_del = Column(SmallInteger, default=0)

    def __repr__(self):
        return f"<Ticket(id={self.id}, train_number={self.train_number})>"

    def __str__(self):
        return f"<Ticket(id={self.id}, train_number={self.train_number})>"


class TicketDao:

    @staticmethod
    def insert(ticket: Ticket):
        if sqldb.session.query(Ticket).filter(Ticket.order_no == ticket.order_no).all():
            log(f"订单号：{ticket.order_no}已经存在！")
            return
        sqldb.session.add(ticket)
        sqldb.session.commit()
        log(f"订单号：{ticket.order_no}添加成功！")

    @staticmethod
    def query_ticket(order_no: str) -> Optional[Ticket]:
        return sqldb.session.query(Ticket).filter(Ticket.order_no == order_no).first()

    @staticmethod
    def all_not_handle_tickets() -> List[Ticket]:
        return sqldb.session.query(Ticket).filter(
            or_(
                Ticket.dingding_event_id == "",
                Ticket.dingding_event_id is None,
            ), and_(Ticket.is_del == 0)
        ).all()

    @staticmethod
    def create_event_success(ticket_no: str, event_id: str):
        update_dict = {
            Ticket.dingding_event_id: event_id
        }
        sqldb.session.query(Ticket).filter(Ticket.order_no == ticket_no).update(update_dict,
                                                                                synchronize_session='fetch')
        sqldb.session.commit()

    @staticmethod
    def del_ticket(ticket_no: str) -> Optional[Ticket]:
        ticket = sqldb.session.query(Ticket).filter(Ticket.order_no == ticket_no).first()
        if ticket:
            ticket.is_del = 1
            sqldb.session.commit()
        return ticket
